/********************************************************************************
 *@description: 抽奖新增、编辑、详情
 *@author: Xhd
 *@API: 纪浩然
 *@date: 2024-01-16 13:48:01
 *@version: V1.0.0
**********************************************************************************/

import React, { Component } from 'react';
import GoBack from "@/components/TheGoBack";
import { Form, Input, InputNumber, Radio, Select, DatePicker, Button, message, Space, Modal } from 'antd';
// import Goods from "./goods";
import Prize from "./prize";
import moment from 'moment';
import { apiAddLotteryDrawTurntable, apiGetLotteryDrawTurntableDetail, apiFindLotteryDrawTurntableSweepstakesDetail } from '@/request/lotteryTools';

const { RangePicker } = DatePicker;

class Name extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef();
    this.PromotionsBox = React.createRef();
    this.prizeRef = React.createRef();
    this.state = {
      lotteryDrawTurntableId: "",
      title: "",
      columns: [],
      dataSource: [],
      pageData: { pageNo: 1, pageSize: 10 },
      total: 0,
      searchValue: {},
      searchOption: [],
      onceConsumeMsg: "",
      activityEndTime: "",
      lotteryDrawPrizeAddDtos: [],
      disabled: false,
      type: "",
      loading: false,
      invalidPrizeTips: [],
      tipsOpen: false
    }
  }
  componentDidMount() {
    // console.log(this.props.match.params.type);
    let type = this.props.match.params.type
    let lotteryDrawTurntableId = this.props.match.params.id
    if (type === "add") {
      this.setState({
        type,
        title: "新增"
      })
    } else {
      this.getViews(lotteryDrawTurntableId)
      if (type === "view") {
        this.setState({
          type,
          title: "查看",
          disabled: true
        })
      } else if (type === "addModel") {
        this.setState({
          type,
          title: "新增"
        })
      } else {
        this.setState({
          type,
          title: "编辑",
          lotteryDrawTurntableId
        })
      }
    }
  }
  getViews = async (lotteryDrawTurntableId) => {
    let res = ''
    if (this.props.match.params.type === 'addModel') {
      res = await apiFindLotteryDrawTurntableSweepstakesDetail({ lotteryDrawTurntableId })
    } else {
      res = await apiGetLotteryDrawTurntableDetail({ lotteryDrawTurntableId })
    }
    if (res.code === 0) {
      let newData = res.data
      newData.time = [moment(newData.activityStartTime), moment(newData.activityEndTime)]
      let invalidPrizeTips = newData.invalidPrizeTips ? newData.invalidPrizeTips.split("\n") : []
      this.setState({ activityEndTime: newData.activityEndTime, invalidPrizeTips: invalidPrizeTips })
      if(newData.invalidPrizeTips && newData.invalidPrizeTips.length > 0) {
        this.setState({tipsOpen: true})
      }
      this.formRef.current.setFieldsValue(newData)
      let arr = [], result = [], goodsSku = []
      newData.lotteryDrawPrizeDetailDtos.map(item => {
        arr.push(item.prizePrefectureName)
        // item.prizePrefectureName
      })
      for (let i = 0; i < arr.length; i++) {
        if (!result.includes(arr[i])) {
          result.push(arr[i]);
        }
      }
      // console.log(result);
      const len = result.length;
      for (let i = 0; i < len; i += 1) {
        goodsSku.push([result.slice(i, i + 1)[0], [], null, true, "", null, null, false, false]);
        // goodsSku[i].push([])
        for (let j = 0; j < newData.lotteryDrawPrizeDetailDtos.length; j++) {
          if (result.slice(i, i + 1)[0] === newData.lotteryDrawPrizeDetailDtos[j].prizePrefectureName) {
            goodsSku[i][1].push(newData.lotteryDrawPrizeDetailDtos[j])
            if(this.props.match.params.type === 'addModel') {
              goodsSku[i][1].map(v=>{
                v.lotteryDrawPrizeId = null
              })
            }
            goodsSku[i][4] = newData.lotteryDrawPrizeDetailDtos[j].prizeLevel
            goodsSku[i][5] = newData.lotteryDrawPrizeDetailDtos[j].prizeWeight
            goodsSku[i][6] = newData.lotteryDrawPrizeDetailDtos[j].prizeMinimum !== 0 ? newData.lotteryDrawPrizeDetailDtos[j].prizeMinimum : null
            goodsSku[i][1].map(item => {
              item.prizeOpenid = item.prizeOpenid ? item.prizeOpenid : "--"
              // item.prizeCost = item.prizeCost/100
              item.fileList = [{
                uid: '-1',
                name: "image",
                url: item.prizeImages
              }]
            })
          }
        }
      }
      goodsSku.map(item => {
        item[1].map(item2 => {
          item2.prizeCost = parseInt((item2.prizeCost / 100).toFixed(0))
          if (item2.prizeType === "CB") {
            item2.prizeCount = item2.prizeCount / 10
          }
        })
      })
      // console.log(goodsSku);
      this.prizeRef.current.setState({
        goodsSku,
      })
      // console.log(goodsSku);
    }
  }
  // 单次消耗为10的倍数
  onceConsumeChange = (value) => {
    if (value % 10 !== 0) {
      this.setState({
        onceConsumeMsg: { message: "单次消耗需为10的倍数" }
      })
    } else {
      this.setState({
        onceConsumeMsg: ""
      })
    }
  }
  //活动时间
  activityTime = (val) => {
    if (val) {
      let activityEndTime = moment(val[1]).format("YYYY-MM-DD")
      this.setState({
        activityEndTime
      })
    }
  }
  addGoodsSku(value) {
    // console.log(value);
    value.forEach((item, index) => {
      item[1].forEach((item2, key1) => {
        if (item2.prizeType === "HHD" || item2.prizeType === "CB") {
          if (!item2.prizeCount) {
            value[index][1][key1].prizeCountFalg = true
            // this.prizeRef.current.setState({
            //   goodsSku: value
            // })
          } else {
            value[index][1][key1].prizeCountFalg = false
            // this.prizeRef.current.setState({
            //   goodsSku: value
            // })
          }
        }
        if (!item2.prizeName) {
          value[index][1][key1].prizeNameFalg = true
          // this.prizeRef.current.setState({
          //   goodsSku: value
          // })
        } else {
          value[index][1][key1].prizeNameFalg = false
          // this.prizeRef.current.setState({
          //   goodsSku: value
          // })
        }
        if (!item2.prizeImages) {
          value[index][1][key1].prizeImagesFalg = true
          // this.prizeRef.current.setState({
          //   goodsSku: value
          // })
        } else {
          value[index][1][key1].prizeImagesFalg = false
          // this.prizeRef.current.setState({
          //   goodsSku: value
          // })
        }
        if (!item2.prizeCost) {
          value[index][1][key1].prizeCostFalg = true
          // this.prizeRef.current.setState({
          //   goodsSku: value
          // })
        } else {
          value[index][1][key1].prizeCostFalg = false
          // this.prizeRef.current.setState({
          //   goodsSku: value
          // })
        }
        // if (item2.prizeType === "SW") {
        //   if (!item2.prizeValidityPeriod) {
        //     value[index][1][key1].prizeValidityPeriodFalg = true
        //     // this.prizeRef.current.setState({
        //     //   goodsSku: value
        //     // })
        //   } else {
        //     value[index][1][key1].prizeValidityPeriodFalg = false
        //     // this.prizeRef.current.setState({
        //     //   goodsSku: value
        //     // })
        //   }
        // }
      })
    })
    let lotteryDrawPrizeAddDtos = this.getLotteryDrawPrizeAddDtos()
    this.formRef.current.setFieldsValue({
      lotteryDrawPrizeAddDtos
    })
  }
  //奖品校验
  checkGoodsSku(rules, value, callback) {
    return new Promise((resolve, reject) => {
      // value = this.prizeRef.current.state.prizeData
      value = this.prizeRef.current.state.goodsSku
      let goodsSku = this.prizeRef.current.state.goodsSku
      let flag = true, hasEmpty = true, hasJoin = true, itemFlag = true
      if (value.length > 0) {
        let num = 0
        value.forEach(item => {
          num += item[1].length
        })
        if (num < 8) {
          flag = false
          hasEmpty = false
          reject('请累计添加最少8个奖品！')
        }
        value.forEach((item, index) => {
          if (item[1].length === 0) {
            flag = false
            hasEmpty = false
            goodsSku[index][7] = true
            this.prizeRef.current.setState({
              goodsSku
            })
            reject('请添加奖品！')
          }
          if (item[5] === null) {
            flag = false
            hasEmpty = false
            goodsSku[index][8] = true
            this.prizeRef.current.setState({
              goodsSku
            })
            reject('请填写中奖权重')
          }
          item[1].forEach((item2, key1) => {
            if (item2.prizeType === "HHD" || item2.prizeType === "CB") {
              if (!item2.prizeCount) {
                itemFlag = false
                goodsSku[index][1][key1].prizeCountFalg = true
                this.prizeRef.current.setState({
                  goodsSku
                })
              } else {
                goodsSku[index][1][key1].prizeCountFalg = false
                this.prizeRef.current.setState({
                  goodsSku
                })
              }
            }
            if (!item2.prizeName) {
              itemFlag = false
              goodsSku[index][1][key1].prizeNameFalg = true
              this.prizeRef.current.setState({
                goodsSku
              })
            } else {
              goodsSku[index][1][key1].prizeNameFalg = false
              this.prizeRef.current.setState({
                goodsSku
              })
            }
            if (!item2.prizeImages) {
              itemFlag = false
              goodsSku[index][1][key1].prizeImagesFalg = true
              this.prizeRef.current.setState({
                goodsSku
              })
            } else {
              goodsSku[index][1][key1].prizeImagesFalg = false
              this.prizeRef.current.setState({
                goodsSku
              })
            }
            if (!item2.prizeCost) {
              itemFlag = false
              goodsSku[index][1][key1].prizeCostFalg = true
              this.prizeRef.current.setState({
                goodsSku
              })
            } else {
              goodsSku[index][1][key1].prizeCostFalg = false
              this.prizeRef.current.setState({
                goodsSku
              })
            }
            // if (item2.prizeType === "SW") {
            //   if (!item2.prizeValidityPeriod) {
            //     itemFlag = false
            //     goodsSku[index][1][key1].prizeValidityPeriodFalg = true
            //     this.prizeRef.current.setState({
            //       goodsSku
            //     })
            //   } else {
            //     goodsSku[index][1][key1].prizeValidityPeriodFalg = false
            //     this.prizeRef.current.setState({
            //       goodsSku
            //     })
            //   }
            // }
          })
        })
        if (itemFlag) {
          resolve();
        }
      } else {
        if ((value && value.length > 0 && flag)) {
          resolve()
        } else {
          if (!hasEmpty) {
            return
          }
          if (!hasJoin) {
            resolve();
          }
          if (!flag) {
            resolve();
          }
          reject('请添加奖品专区！')
        }
      }
    })
  }

  getLotteryDrawPrizeAddDtos = () => {
    let val = this.prizeRef.current.state
    // let arr = val.prizeData
    let arr = val.goodsSku
    let newArr = []
    arr.map((item, index) => {
      if (item[1].length > 0) {
        item[1].map((v, k) => {
          if (v.prizeType === "CB") {
            v.prizeCount = v.prizeCount * 10
          }
          newArr.push({
            ...v,
            prizeCost: v.prizeCost * 100,
            prizeWeight: item[5],
            prizeMinimum: item[6] ? item[6] : 0,
            prizeLevel: item[4],
          })
        })
      }
    })
    return newArr
  }

  onFinish = async (values) => {
    this.setState({ loading: true })
    const { lotteryDrawTurntableId } = this.state
    let lotteryDrawPrizeAddDtos = this.getLotteryDrawPrizeAddDtos()
    values.activityStartTime = moment(values.time[0]).format("YYYY-MM-DD")
    values.activityEndTime = moment(values.time[1]).format("YYYY-MM-DD")
    values.lotteryDrawPrizeAddDtos = lotteryDrawPrizeAddDtos
    delete (values.time)
    console.log(values);
    if (lotteryDrawTurntableId !== 'null') {
      await apiAddLotteryDrawTurntable({ lotteryDrawTurntableId, ...values }).then(res => {
        if (res.code === 0) {
          message.success({
            content: "编辑成功",
            duration: 3
          })
          this.props.history.goBack(-1)
        }
        this.setState({ loading: false })
      })
    } else {
      await apiAddLotteryDrawTurntable(values).then(res => {
        if (res.code === 0) {
          message.success({
            content: "新增成功",
            duration: 3
          })
          this.props.history.goBack(-1)
        }
        this.setState({ loading: false })
      })
    }
  }
  render() {
    const { title, columns, dataSource, pageData: { pageNo, pageSize }, total, searchOption, onceConsumeMsg, initialValues, blackGoodsKey,
      checkIng, goodsSku, activityEndTime, type, disabled, lotteryDrawTurntableId, loading, invalidPrizeTips, tipsOpen
    } = this.state;
    let redemptionDeadline = <div><span style={{color: 'red'}}>*</span>兑奖截止时间</div>
    console.log(invalidPrizeTips);
    return (<div className='p-layout-box'>
      <GoBack history={this.props.history} title={title + "抽奖转盘"} />
      <Form ref={this.formRef} onFinish={(values) => this.onFinish(values)} initialValues={initialValues}
        labelCol={{ span: 2, }} wrapperCol={{ span: 24, }}
      >
        <div style={{ background: "#ddd", fontWeight: 700, fontSize: "25px", paddingLeft: "20px", margin: "5px 0px" }}>
          基本信息
        </div>
        <Form.Item label="活动名称" name={"turntableName"} rules={[{ required: true, max: 20 }]} >
          <Input placeholder='请输入名称' style={{ width: "300px" }} disabled={disabled} />
        </Form.Item>
        <Form.Item label="奖池类型" name={"turntableType"} rules={[{ required: true }]} >
          <Select
            style={{ width: "300px" }}
            disabled={disabled}
            placeholder="请选择类型"
            options={[
              {
                value: '1',
                label: '猫',
              },
              {
                value: '0',
                label: '狗',
              },
            ]}
          >
          </Select>
        </Form.Item>
        <Form.Item label="消耗类型" name={"consumeType"} rules={[{ required: true }]} >
          <Radio.Group style={{ width: "300px" }} disabled={disabled}>
            <Radio value={"HHD"} >哈哈豆</Radio>
            <Radio value={"CB"} disabled >宠币</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="单次消耗" name={"onceConsume"} rules={[{ required: true }, {
          validator: (_, value) => {
            if (value < 10 || value > 990) {
              return Promise.reject(`单次消耗需为10 ~ 990之间.`);
            }
            if (value % 10 !== 0) {
              return Promise.reject(`单次消耗需为10的倍数`);
            }
            return Promise.resolve();
          },
        }]} >
          <InputNumber style={{ width: "300px" }} disabled={disabled} />
        </Form.Item>
        <Form.Item label="每日抽奖上限" name={"lotteryDrawUpperLimit"} rules={[{ required: true }]} >
          <InputNumber precision={0} min={1} max={100} style={{ width: "300px" }} disabled={disabled} />
        </Form.Item>
        <Form.Item label="活动日期" name={"time"} rules={[{ required: true }]} >
          <RangePicker onChange={(value) => this.activityTime(value)} style={{ width: "300px" }} disabled={disabled} />
        </Form.Item>
        <Form.Item label={redemptionDeadline}>
          <>
            <span>活动结束</span>
            <Form.Item noStyle name={"redemptionDeadline"} rules={[{ required: true, message: '请输入兑奖截止时间' }]}>
              <InputNumber precision={0} min={1} max={99} style={{ width: "150px" }} disabled={disabled} />
            </Form.Item>
            <span>天后截止兑换实物</span>
          </>
        </Form.Item>

        <div style={{ background: "#ddd", fontWeight: 700, fontSize: "25px", paddingLeft: "20px", margin: "5px 0px" }}>
          奖品设置
        </div>

        <Form.Item label="奖品" name={"lotteryDrawPrizeAddDtos"} rules={[{
          required: true,
          validator: this.checkGoodsSku.bind(this)
        }]} >
          <Prize ref={this.prizeRef} activityEndTime={activityEndTime} disabled={disabled} lotteryDrawTurntableId={lotteryDrawTurntableId} addGoodsSku={this.addGoodsSku.bind(this)} ></Prize>
        </Form.Item>
        {
          type !== "view" && <Form.Item style={{ textAlign: "center" }}>
            <Space>
              <Button onClick={() => this.props.history.goBack(-1)}>取消</Button>
              <Button type='primary' htmlType='submit' loading={loading} >确定</Button>
            </Space>
          </Form.Item>
        }
      </Form>
      <Modal open={tipsOpen} footer={null} closable={false} >
        <div style={{textAlign: 'center', fontSize: '24px', lineHeight: '40px'}}>
          温馨提示
        </div>
        以下奖品已失效，请重新添加：<br />
        {/* {invalidPrizeTips} */}
        {invalidPrizeTips.map(v=>{
          return <p>{v}</p>
        })}
        <div style={{width: '100%', marginTop: '10px'}}>
          <Button type='default' onClick={()=>this.setState({tipsOpen: false})} style={{width: '100%'}}>我知道了</Button>
        </div>
      </Modal>
    </div>)
  }
}

export default Name